home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c,comp.unix.programmer
- Subject: Re: Q: '\n' character
- Date: Sat, 13 Apr 96 11:54:33 GMT
- Organization: none
- Message-ID: <829396473snz@genesis.demon.co.uk>
- References: <4kj66f$k0o@ren.cei.net> <1996Apr11.192937.25676@sq.com>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <1996Apr11.192937.25676@sq.com> msb@sq.com "Mark Brader" writes:
-
- >> > Is there a function or some sort of way that I could remove '\n'
- >> > charecter form the end of the string.
- >>
- >> fgets(buffer, file);
- >> buffer[strlen(buffer)-1]=0;
- >>
- >> It may not be the fastest, but it is darned near the easiest.
- >
- >Or the buggiest. Instead use:
- >
- > len = strlen (buffer);
- > if (len > 0 && buffer[len-1] == '\n') buffer[len-1] = '\0';
- >
- >Both tests in the "if" are necessary.
-
- Not exactly true. fgets() can never place a zero length string in the
- buffer. However its return value can be a null pointer on end-of-file or
- failure and that condition must be tested for. fgets() will leave the buffer
- unchanged if it encounters end-of-file but that is the only case where
- you could legally test for and possibly find a zero length string. So the
- code should look something like:
-
- if (fgets(buffer, file) != NULL) {
- size_t len = strlen(buffer);
-
- if (buffer[len-1] == '\n') buffer[len-1] = '\0';
- }
-
- >In the specific case of a string obtained from fgets(), we can be
- >sure that if there is a newline then it is the last character.
- >This leads to the alternative approach:
- >
- > ptr = strchr (buffer, '\n'); /* or strrchr() */
- > if (ptr) *ptr = '\0';
-
- Or the very alternative approach:
-
- strtok(buffer, "\n");
-
- But in both cases you still need to test the return code of fgets().
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-